package se137.hrbust.hlgshopping137.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import se137.hrbust.hlgshopping137.dto.LoginRequest137;
import se137.hrbust.hlgshopping137.dto.LoginResponse137;
import se137.hrbust.hlgshopping137.entity.User137;
import se137.hrbust.hlgshopping137.mapper.UserMapper137;
import se137.hrbust.hlgshopping137.service.UserService137;
import se137.hrbust.hlgshopping137.utils.JwtUtil137;
import se137.hrbust.hlgshopping137.utils.RedisUtil137;

@Service
public class UserService137Impl implements UserService137 {
    @Autowired
    UserMapper137 userMapper137;
    @Autowired
    JwtUtil137 jwtUtil;
    @Autowired
    RedisUtil137 redisUtil;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void addUser(User137 user) {
        userMapper137.insert(user);
    }

    @Override
    public void editUser(User137 user) {
        userMapper137.updateById(user);
    }

    @Override
    public void deleteUser(int id) {
        userMapper137.deleteById(id);
    }

    @Override
    public User137 findUserById(int id) {

        return userMapper137.selectById(id);
    }

    @Override
    public User137 findUserByCode(String userCode) {
        QueryWrapper<User137> queryWrapper = new QueryWrapper<>();
        //对后端查询出来的密码进行md5加密之后再比较
//        queryWrapper.eq("FUserPass137",bCryptPasswordEncoder.encode(userCode));

        queryWrapper.eq("FUserCode137", userCode);
        System.out.println(userCode);
        return userMapper137.selectList(queryWrapper).get(0);
    }

    @Override
    public LoginResponse137 login(LoginRequest137 loginRequest) {
        User137 user = userMapper137.findUserByUserCode(loginRequest.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        if (!passwordEncoder.matches(loginRequest.getPassword(), user.getUserPass137())) {
            throw new RuntimeException("password error");
        }
        String jwt = jwtUtil.generateToken(user.getUserCode137());
        String refreshToken = jwtUtil.generateRefreshToken(user.getUserCode137());
        redisUtil.setUserToken(user.getUserCode137(), jwt);
        LoginResponse137 response = new LoginResponse137();
        response.setToken(refreshToken);
        response.setUserName(user.getUserCode137());
        response.setUserId(user.getUserId137());
        return response;
    }

    @Override
    public boolean logout(String token) {
        if (jwtUtil.validateToken(token) && !jwtUtil.isTokenExpired(token)) {
            String username = jwtUtil.getUsernameFromToken(token);
            redisUtil.deleteUserToken(username);
            return true;
        }
        return false;
    }

    @Override
    public boolean validateToken(String token) {
        if (!jwtUtil.validateToken(token)) {
            return false;
        }

        if (jwtUtil.isTokenExpired(token)) {
            return false;
        }

        String username = jwtUtil.getUsernameFromToken(token);
        String redisToken = redisUtil.getUserToken(username);

        return token.equals(redisToken);
    }

    @Override
    public User137 getUserByUsername(String username) {
        return userMapper137.findUserByUserCode(username);
    }

    @Override
    public void register(User137 user) {

        User137 exist = userMapper137.findUserByUserCode(user.getUserCode137());
        if (exist != null) {
            throw new RuntimeException("用户已存在");
        }
        if (user.getUserPass137() == null || user.getUserPass137().isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }
        String hashed = passwordEncoder.encode(user.getUserPass137());
        user.setUserPass137(hashed);
        if (user.getUserRole137() == null || user.getUserRole137().isEmpty()) {
            // 假设 USER 对应整数值 1，需要根据实际业务需求调整
            user.setUserRole137("1"); // 或者直接 user.setUserRole137(1)（如果字段类型是Integer）
        }
        userMapper137.insert(user);
    }
}



